<script lang="ts" setup>
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'

import type { BreadcrumbRoute } from '@arco-design/web-vue'

const { t } = useI18n({ useScope: 'global' })
const route = useRoute()

const routes = computed<BreadcrumbRoute[]>(() => {
  const hasBreadcrumbRoutes = route.matched.filter(
    ({ meta: { menuTitle, hideBreadcrumb } }, i, routes) => {
      return (
        menuTitle !== undefined && !hideBreadcrumb && routes[i + 1]?.meta.menuTitle !== menuTitle
      )
    }
  )
  if (hasBreadcrumbRoutes.length === 0) return []
  hasBreadcrumbRoutes[hasBreadcrumbRoutes.length - 1].meta.isLink = false

  return hasBreadcrumbRoutes.map(({ path, meta, name }) => ({
    name,
    path,
    label: meta.menuTitle!,
    isLink:
      meta.isLink !== false && path !== route.path && name !== undefined && name !== route.name
  }))
})
</script>

<template>
  <div class="flex items-center select-none">
    <i v-if="routes.length !== 0" class="i-fluent-location-24-filled text-arco-3 text-lg mr-.5" />
    <a-breadcrumb
      :routes
      class="[&>[aria-hidden]]:mx-0 [&>[role=listitem]:last-child>span]:border-b-dashed"
    >
      <template #separator>
        <i class="i-fluent-divider-tall-16-filled -rotate-15 block" />
      </template>
      <template
        #item-render="{
          route: { isLink, label, name }
        }: {
          route: BreadcrumbRoute & { isLink: boolean; name?: string }
        }"
      >
        <RouterLink
          v-if="isLink"
          :to="{
            name,
            query: route.query,
            params: route.params
          }"
        >
          <span>{{ t(label) }}</span>
        </RouterLink>

        <span v-else class="text-arco-2 font-bold border-b-1">{{ t(label) }}</span>
      </template>
    </a-breadcrumb>
  </div>
</template>
